﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.Management;
using System.Threading;
using System.Net;
using System.Net.NetworkInformation;
using Conectorws;

namespace GenVisitas
{
    public partial class Form1 : Form
    {
        public static List<string> lstProxies;
        public static int iterador = 0;
        public static int ciclos = 0;
        public static int iteradorProxy = 0;
        public static int visitasxIP = 0;
        public static int iteradorVisitas;
        public static string[][] direccionesIP = new string[500][];
        public static int cantidadIPs = 0;
        public static int iteradorIP;
        public static string Usuario;
        public static bool isAdmin=false;
        private string IP;
        public login frmLogin;
        private string urlDestino;
        private Thread procesoServicio;

        public struct Struct_INTERNET_PROXY_INFO
        {
            public int dwAccessType;
            public IntPtr proxy;
            public IntPtr proxyBypass;
        }

        private void obtieneIP(){
            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    IP = ip.ToString() + "-" + IP;
                }
            }           
        }

        private void AlmacenarEnLog() {
            ServicioCN.guardaLog(Usuario, urlDestino, IP);
        }

        [DllImport("wininet.dll", SetLastError = true)]
        private extern static bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);        

        private void UseProxy(string strProxy)
        {
            Form1.Struct_INTERNET_PROXY_INFO internetProxyInfo;
            internetProxyInfo.dwAccessType = 3;
            internetProxyInfo.proxy = Marshal.StringToHGlobalAnsi(strProxy);
            internetProxyInfo.proxyBypass = Marshal.StringToHGlobalAnsi("local");
            IntPtr num = Marshal.AllocCoTaskMem(Marshal.SizeOf((object)internetProxyInfo));
            Marshal.StructureToPtr((object)internetProxyInfo, num, true);
            Form1.InternetSetOption(IntPtr.Zero, 38, num, Marshal.SizeOf((object)internetProxyInfo));
        }

        public static void SetIP(string IpAddresses,
  string SubnetMask, string Gateway, string DnsSearchOrder)
        {
            ManagementClass mc = new ManagementClass(
              "Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                // Make sure this is a IP enabled device. 
                // Not something like memory card or VM Ware
                if ((bool)mo["IPEnabled"])
                {
                    /*
                    if (mo["Caption"].Equals(nicName))
                    {*/

                    ManagementBaseObject newIP =
                      mo.GetMethodParameters("EnableStatic");
                    ManagementBaseObject newGate =
                      mo.GetMethodParameters("SetGateways");
                    ManagementBaseObject newDNS =
                      mo.GetMethodParameters("SetDNSServerSearchOrder");

                    newGate["DefaultIPGateway"] = new string[] { Gateway };
                    newGate["GatewayCostMetric"] = new int[] { 1 };

                    newIP["IPAddress"] = IpAddresses.Split(',');
                    newIP["SubnetMask"] = new string[] { SubnetMask };

                    newDNS["DNSServerSearchOrder"] = DnsSearchOrder.Split(',');

                    ManagementBaseObject setIP = mo.InvokeMethod(
                      "EnableStatic", newIP, null);
                    ManagementBaseObject setGateways = mo.InvokeMethod(
                      "SetGateways", newGate, null);
                    ManagementBaseObject setDNS = mo.InvokeMethod(
                      "SetDNSServerSearchOrder", newDNS, null);

                    break;
                    /*}*/
                }
            }
        }

        public void cargarListadoProxies()
        {
            StreamReader objReader = new StreamReader("proxies.txt");
            lstProxies = new List<string>();
            lstProxies.Clear();
            string txt = "";
            while (txt != null)
            {
                txt = objReader.ReadLine();
                lstProxies.Add(txt);
            }
            lblProxy.Text = lstProxies[0];
            objReader.Close();
        }

        public void cargarListadoIPs()
        {
            cantidadIPs = 0;
            StreamReader objReader = new StreamReader("configIP.txt");
            string txt = "";
            while (txt != null && cantidadIPs < 500)
            {
                txt = objReader.ReadLine();
                if (txt != null && !txt.StartsWith("//"))
                {
                    direccionesIP[cantidadIPs] = txt.Split('-');
                    cantidadIPs++;
                }
            }
            objReader.Close();
        }

        public Form1()
        {
            InitializeComponent();
            obtieneIP();
            timer1.Enabled = false;
            button3.Visible = false;
            panel1.Visible = false;
            dateTimePicker1.Value = DateTime.Now.AddHours(2);
            checkBox1.Checked = true;
            //SetIP("6.6.6.9", "255.255.255.0", "6.6.6.1", "8.8.8.8,8.8.4.4");
        }

        private void Habilitar_Deshabilitar()
        {
            button2.Visible = !button2.Visible;
            button3.Visible = !button3.Visible;
            timer1.Enabled = !timer1.Enabled;
            button1.Enabled = !button1.Enabled;
            panel1.Visible = !panel1.Visible;
            numericUpDown1.Enabled = !numericUpDown1.Enabled;
            button4.Enabled = !button4.Enabled;
            button5.Enabled = !button5.Enabled;
            button6.Enabled = !button6.Enabled;
            checkBox1.Enabled = !checkBox1.Enabled;
            checkBox2.Enabled = !checkBox2.Enabled;
            checkBox3.Enabled = !checkBox3.Enabled;
            numericUpDown2.Enabled = !numericUpDown2.Enabled;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() != "")
            {
                if (textBox1.Text.StartsWith("http://") || textBox1.Text.StartsWith("https://"))
                {
                    listView1.Items.Add(textBox1.Text);
                    textBox1.Text = "";
                }
                else
                {
                    listView1.Items.Add("http://" + textBox1.Text);
                    textBox1.Text = "";
                }
            }
            else
                MessageBox.Show("Ingrese la URL", "Error");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int error = 0;
            try
            {
                if (listView1.Items.Count > 0)
                {
                    if (checkBox1.Checked)
                    {
                        try
                        {
                            cargarListadoProxies();
                        }
                        catch
                        {
                            error = 1;
                            throw;
                        }
                    }
                    if (checkBox3.Checked)
                    {
                        try
                        {
                            cargarListadoIPs();
                        }
                        catch {
                            error = 2;
                            throw;
                        }
                    }

                    ciclos = 0;
                    iterador = 0;
                    iteradorProxy = 0;
                    iteradorVisitas = 0;
                    progressBar1.Step = 1;
                    progressBar1.Maximum = listView1.Items.Count;
                    progressBar1.Value = 0;
                    label5.Text = ciclos.ToString();
                    timer1.Interval = timer1.Interval * (int)numericUpDown1.Value;
                    visitasxIP = (int)numericUpDown2.Value;
                    Habilitar_Deshabilitar();
                }
                else
                    MessageBox.Show("Ingrese las URL´s que desea visitar", "Error");
            }
            catch
            {
                if (error == 1)
                    MessageBox.Show("Coloque el archivo proxies.txt, con la lista de proxies, en la ruta de la aplicación", "Error");
                if (error == 2)
                    MessageBox.Show("Coloque el archivo configIP.txt, con la lista de ips, en la ruta de la aplicación", "Error");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (dateTimePicker1.Value.CompareTo(DateTime.Now) < 0)
            {
                button3_Click(sender, e);
            }
            else
            {                
                if (iterador >= listView1.Items.Count)
                {
                    iterador = 0;
                    progressBar1.Value = 0;
                    ciclos++;
                    label5.Text = ciclos.ToString();
                    if (checkBox1.Checked)
                    {
                        iteradorProxy++;
                        lblProxy.Text = lstProxies[iteradorProxy];
                    }
                }
                if (checkBox1.Checked)
                {
                    if (iteradorProxy > lstProxies.Count - 1)
                        iteradorProxy = 0;
                    this.UseProxy(lstProxies[iteradorProxy]);
                }
                else
                {
                    this.UseProxy("127.0.0.1:");
                }

                urlDestino = listView1.Items[iterador].Text;
                webBrowser1.Navigate(listView1.Items[iterador].Text);
                webBrowser2.Navigate(listView1.Items[iterador].Text);
                
                procesoServicio = new Thread(new ThreadStart(AlmacenarEnLog));
                procesoServicio.Start();
                progressBar1.Increment(progressBar1.Step);
                iterador++;
                iteradorVisitas++;
                if (iteradorVisitas % visitasxIP == 0 && checkBox3.Checked)
                {
                    if (iteradorIP >= cantidadIPs)
                        iteradorIP = 0;
                    SetIP(direccionesIP[iteradorIP][0], direccionesIP[iteradorIP][1], direccionesIP[iteradorIP][2], direccionesIP[iteradorIP][3]);
                    iteradorIP++;
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("");
            webBrowser2.Navigate("");
            Habilitar_Deshabilitar();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                listView1.Items.Remove(listView1.SelectedItems[0]);
            }
            else
            {
                MessageBox.Show("Seleccione la URL que desea quitar", "Error");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //cargar direcciones de txt
            try
            {
                StreamReader objReader = new StreamReader("direcciones.txt");

                string sLine = "";
                while (sLine != null)
                {
                    sLine = objReader.ReadLine();
                    listView1.Items.Add(sLine);
                }
                objReader.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Creer un archivo direcciones.txt que contenga las URL's, en la ruta del ejecutable", "Error");
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            List<string> urls = ServicioCN.obtieneListadoURLs();
            for (int i = 0; i < urls.Count; i++) {
                listView1.Items.Add(urls[i]);
            }
            //cargar direcciones de web service
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDown2.Visible = checkBox3.Checked;
            label8.Visible = checkBox3.Checked;
            label7.Visible = checkBox3.Checked;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                procesoServicio.Abort();
            }
            catch
            { 
            }
            frmLogin.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (isAdmin)
                button7.Visible = true;
            else
                button7.Visible = false;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Informe frm = new Informe();
            frm.Show();
        }
    }
}
